package com.cjkj.equipment.service.impl;

import com.cjkj.common.core.constant.WarnConstants;
import com.cjkj.common.core.utils.DateUtils;
import com.cjkj.common.core.utils.bean.BeanUtils;
import com.cjkj.equipment.domain.TWarnHandleRecords;
import com.cjkj.equipment.domain.TWarnRecords;
import com.cjkj.equipment.domain.TWarnSetting;
import com.cjkj.equipment.mapper.TWarnHandleRecordsMapper;
import com.cjkj.equipment.mapper.TWarnRecordsMapper;
import com.cjkj.equipment.mapper.TWarnSettingMapper;
import com.cjkj.equipment.service.ITWarnRecordsService;
import com.cjkj.system.api.domain.APIWarnHandle;
import com.cjkj.system.api.domain.request.WarnRecordReq;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 预警记录Service业务层处理
 * 
 * @author cjkj
 * @date 2024-08-30
 */
@Service
public class TWarnRecordsServiceImpl implements ITWarnRecordsService 
{
    @Resource
    private TWarnRecordsMapper tWarnRecordsMapper;
    @Resource
    private TWarnSettingMapper tWarnSettingMapper;
    @Resource
    private TWarnHandleRecordsMapper tWarnHandleRecordsMapper;

    @Override
    public boolean saveOrUpdateRecord(List<TWarnRecords> records) {

        AtomicInteger count = new AtomicInteger();
        if(records != null && !records.isEmpty()){
            for(TWarnRecords e : records) {
                TWarnRecords query = new TWarnRecords();
                query.setVisitNo(e.getVisitNo());
                if(e.getWarnType() != null) {
                    query.setWarnType(e.getWarnType());
                }
                query.setWarnContent(e.getWarnContent());
                query.setHasHandle(WarnConstants.WARN_HANDLE_UNPROCESSED);
                TWarnRecords record = tWarnRecordsMapper.selectOne(query);

                if(record != null){
                    BeanUtils.copyProperties(record, e);
                    e.setWarnCount(e.getWarnCount() + 1);
                    count.addAndGet(tWarnRecordsMapper.updateTWarnRecords(e));
                } else {
                    e.setWarnCount(1);
                    count.addAndGet(tWarnRecordsMapper.insertTWarnRecords(e));
                }
            }
            return count.get() == records.size();
        }

        return false;
    }

    @Override
    public List<TWarnRecords> listRecords(String hospitalId, String deptId, String hasHandle, String dataType) {
        return tWarnRecordsMapper.selectList(hospitalId, deptId, hasHandle, dataType);
    }

    /**
     * 1.增加预警处理记录
     * 2.判断预警处理方式，更新预警消息状态
     * */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Boolean handleWarn(List<APIWarnHandle> warnHandleList) {
        // 查询预警设置
        List<TWarnSetting> warnSettings = tWarnSettingMapper.selectTWarnSettingList(null);
        Map<String,Object> settingMap = new HashMap<>();
        warnSettings.forEach(e -> settingMap.put(e.getWarnType(), e));

        Date now = DateUtils.getNowDate();
        int flag = 0;
        for (APIWarnHandle e : warnHandleList) {
            // 添加处理记录
            TWarnHandleRecords warnHandleRecord = new TWarnHandleRecords();
            warnHandleRecord.setWarnRecordId(e.getWarnId());
            warnHandleRecord.setHospitalId(e.getHospitalId());
            warnHandleRecord.setDeptId(e.getDeptId());
            warnHandleRecord.setHandleBy(e.getHandlerId());
            warnHandleRecord.setHandleWay(e.getHandleWay());
            warnHandleRecord.setHandleTime(now);
            int handleFlag = tWarnHandleRecordsMapper.insertTWarnHandleRecords(warnHandleRecord);

            // 修改预警消息状态
            TWarnRecords warnRecord = new TWarnRecords();
            warnRecord.setId(e.getWarnId());
            warnRecord.setHandleWay(e.getHandleWay());
            if(WarnConstants.WARN_HANDLE_WAY_SOLVED.equals(e.getHandleWay())){
                warnRecord.setHasHandle(WarnConstants.WARN_HANDLE_PROCESSED);
                warnRecord.setHandleTime(now);
            }else if(WarnConstants.WARN_HANDLE_WAY_REMIND_LATER.equals(e.getHandleWay())){
                setNextReminderTime(settingMap, warnRecord, e.getWarnType());
            }

            int recordsFlag = tWarnRecordsMapper.updateTWarnRecords(warnRecord);
            if(handleFlag > 0 && recordsFlag > 0) {
                flag ++;
            }
        }

        return flag == warnHandleList.size();
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean handleWarn(WarnRecordReq req) {
        // 查询患者预警信息
        TWarnRecords query = new TWarnRecords();
        query.setVisitNo(req.getVisitNo());
        query.setHasHandle(WarnConstants.WARN_HANDLE_UNPROCESSED);
        List<TWarnRecords> warnRecordsList = tWarnRecordsMapper.selectTWarnRecordsList(query);

        // 查询预警设置
        List<TWarnSetting> warnSettings = tWarnSettingMapper.selectTWarnSettingList(null);
        Map<String,Object> settingMap = new HashMap<>();
        warnSettings.forEach(e -> settingMap.put(e.getWarnType(),e));

        int flag = 0;
        for (TWarnRecords e : warnRecordsList) {
            // 添加处理记录
            TWarnHandleRecords warnHandleRecord = new TWarnHandleRecords();
            warnHandleRecord.setWarnRecordId(e.getId());
            warnHandleRecord.setHospitalId(req.getHospitalId());
            warnHandleRecord.setDeptId(req.getDeptId());
            warnHandleRecord.setHandleBy(req.getHandlerId());
            warnHandleRecord.setHandleWay(req.getHandleWay());
            warnHandleRecord.setHandleTime(new Date());
            int handleFlag = tWarnHandleRecordsMapper.insertTWarnHandleRecords(warnHandleRecord);

            // 修改预警消息状态
            e.setHandleWay(req.getHandleWay());
            if(WarnConstants.WARN_HANDLE_WAY_SOLVED.equals(req.getHandleWay())){
                e.setHasHandle(WarnConstants.WARN_HANDLE_PROCESSED);
                e.setHandleTime(new Date());
            }else if(WarnConstants.WARN_HANDLE_WAY_REMIND_LATER.equals(e.getHandleWay())){
                setNextReminderTime(settingMap, e, e.getWarnType());
            }
            int recordsFlag = tWarnRecordsMapper.updateTWarnRecords(e);

            if(handleFlag > 0 && recordsFlag > 0) {
                flag ++;
            }
        }

        return flag == warnRecordsList.size();
    }

    @Override
    public List<TWarnRecords> list(Long visitNo, Date expectOutTime) {
        TWarnRecords query = new TWarnRecords();
        query.setVisitNo(visitNo);
        query.setHasHandle(WarnConstants.WARN_HANDLE_UNPROCESSED);
        query.setCreateTime(expectOutTime);
        return tWarnRecordsMapper.selectTWarnRecordsList(query);
    }

    private void setNextReminderTime(Map<String,Object> map, TWarnRecords record, String warnType){
        /**
         * 1.根据预警类型，获取下次提醒间隔时间
         * 2.根据设置表获取得预警间隔时间，从当前时间往后推算下次提醒时间
         * 3.设置记录中的下次提醒时间
         */
        ObjectMapper objectMapper = new ObjectMapper();
        TWarnSetting warnSetting = objectMapper.convertValue(map.get(warnType), TWarnSetting.class);
        /** 间隔分钟数*/
        String waitTime  = warnSetting.getHoldOnTime();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        calendar.add(Calendar.MINUTE, Integer.parseInt(waitTime));
        record.setNextReminderTime(calendar.getTime());
    }
}
